<?php

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\models\MemberCard;
use app\modules\admin\models\MemberCardSearch;
use app\modules\admin\components\BaseAdminController;
use app\components\Api;
use app\components\Wechat;
use app\components\Loyalty;
use app\components\Log;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\Tenant;

/**
 * MemberCardController implements the CRUD actions for MemberCard model.
 */
class MemberCardController extends BaseAdminController
{
    public function init()
    {
        $identifier = $this->session('identifier');
        $tenant = Tenant::find()->where(['identifier' => $identifier])->all();
        if (count($tenant) != 1) {
            exit('Identifier Miss. 没有设定Tenant');
        }
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all MemberCard models.
     * @return mixed
     */
    public function actionIndex()
    {
        // $re = Wechat::userinfo(['oPPpJuIQfkYCAhbMbWOlmqc_OkAE']);
        // $re = Wechat::card_list(['offset' => 0, 'count' => 50, 'status_list' => ['CARD_STATUS_VERIFY_OK']]);
        // $this->bp($re);
        $searchModel = new MemberCardSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single MemberCard model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $re = Wechat::card_get(['card_id' => $model->card_id]);
        
        if ($re['errmsg'] == 'ok') {
            $card = $re['card']['member_card'];
        } else {
            exit($re['errmsg']);
        }

        $model->logo_url = $card['base_info']['logo_url'];
        $model->code_type = $card['base_info']['code_type'];
        $model->brand_name = $card['base_info']['brand_name'];
        $model->color = $card['base_info']['color'];
        $model->notice = $card['base_info']['notice'];
        $model->description = $card['base_info']['description'];
        $model->prerogative = $card['prerogative'];
        $model->wx_activate_after_submit_url = $card['wx_activate_after_submit_url'];
        $model->quantity = $card['base_info']['sku']['quantity'];
        $model->total_quantity = $card['base_info']['sku']['total_quantity'];
        $model->cost_money_unit = $card['bonus_rule']['cost_money_unit'];
        $model->increase_bonus = $card['bonus_rule']['increase_bonus'];
        $model->max_increase_bonus = $card['bonus_rule']['max_increase_bonus'];
        $model->init_increase_bonus = $card['bonus_rule']['init_increase_bonus'];
        $model->cost_bonus_unit = $card['bonus_rule']['cost_bonus_unit'];
        $model->reduce_money = $card['bonus_rule']['reduce_money'];
        $model->least_money_to_use_bonus = $card['bonus_rule']['least_money_to_use_bonus'];
        $model->max_reduce_bonus = $card['bonus_rule']['max_reduce_bonus'];


        // $this->bp($card);
        return $this->render('view', [
            'model' => $model,
            'card' => $card,
        ]);
    }

    /**
     * Creates a new MemberCard model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new MemberCard();

        if ($model->load(Yii::$app->request->post())) {
            // $this->bp($model);

            $data = [
                'card' => [
                    'card_type' => 'MEMBER_CARD',
                    'member_card' => [
                        'base_info' => [
                            'logo_url' => $model->logo_url, // 卡券的商户logo，建议像素为300*300 必填
                            'code_type' => $model->code_type, // Code展示类型 必填
                            'brand_name' => $model->brand_name, // 商户名字,字数上限为12个汉字 必填
                            'title' => $model->title, // 卡券名，字数上限为9个汉字 必填
                            'color' => $model->color, // 券颜色。按色彩规范标注填写Color010-Color100 必填
                            'notice' => $model->notice, // 卡券使用提醒，字数上限为16个汉字 必填
                            'description' => $model->description, // 卡券使用说明，字数上限为1024个汉字 必填
                            'sku' => [
                                'quantity' => $model->quantity, // 卡券库存的数量 必填
                            ],
                            'date_info' => [
                                'type' => $model->type, // 永久有效类型 必填
                            ],
                            'use_all_locations' => ($model->use_all_locations == 1) ? false : true, // 会员卡是否支持全部门店，填写后商户门店更新时会自动同步至卡券 选填
                            'get_limit' => $model->get_limit, // 每人可领券的数量限制，建议会员卡每人限领一张 选填
                            'pay_info' => [ // 选填
                                'swipe_card' => [ // 选填
                                    'is_swipe_card' => ($model->is_swipe_card == 1) ? false : true, // 是否设置该会员卡支持拉出微信支付刷卡界面 选填
                                    // 'is_pay_and_qrcode' => ($model->is_pay_and_qrcode == 1) ? false : true, // 是否设置该会员卡中部的按钮同时支持微信支付刷卡和会员卡二维码 选填
                                ],
                            ],
                        ],
                        // 'advanced_info' => [],
                        'prerogative' => $model->prerogative, // 会员卡特权说明,限制1024汉字 必填
                        'supply_bonus' => ($model->supply_bonus == 1) ? false : true, // 显示积分，填写true或false，如填写true，积分相关字段均为必填,若设置为true则后续不可以被关闭
                        'supply_balance' => ($model->supply_balance == 1) ? false : true, // 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
                        'wx_activate' => ($model->wx_activate == 1) ? false : true,
                        'wx_activate_after_submit' => ($model->wx_activate_after_submit == 1) ? false : true,
                        'wx_activate_after_submit_url' => $model->wx_activate_after_submit_url,
                        'bonus_rule' => [ // 选填
                            'cost_money_unit' => $model->cost_money_unit, // 消费金额,以分为单位
                            'increase_bonus' => $model->increase_bonus, // 对应增加的积分
                            'max_increase_bonus' => $model->max_increase_bonus, // 用户单次可获取的积分上限
                            'init_increase_bonus' => $model->init_increase_bonus, // 初始设置积分
                            'cost_bonus_unit' => $model->cost_bonus_unit, // 每使用多少积分
                            'reduce_money' => $model->reduce_money, // 抵扣xx元，（这里以分为单位）
                            'least_money_to_use_bonus' => $model->least_money_to_use_bonus, // 抵扣条件，满xx元（这里以分为单位）可用
                            'max_reduce_bonus' => $model->max_reduce_bonus, // 抵扣条件，单笔最多使用xx积分
                        ],
                    ],
                ],
            ];

            // $this->bp(Api::toJSON($data));
            $re = Wechat::card_create($data);
            // $this->bp($re);

            if ($re['errmsg'] != 'ok') {
                Yii::$app->session->setFlash('error', $re['errmsg']);
            } else {
                $card_id = $re['card_id'];
                $model->card_id = $card_id;
                $model->save(false);
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing MemberCard model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $re = Wechat::card_get(['card_id' => $model->card_id]);
        
        if ($re['errmsg'] == 'ok') {
            $card = $re['card']['member_card'];
        } else {
            exit($re['errmsg']);
        }

        $model->logo_url = $card['base_info']['logo_url'];
        $model->code_type = $card['base_info']['code_type'];
        $model->brand_name = $card['base_info']['brand_name'];

        $colors = [
            '#63b359' => 'Color010',
            '#2c9f67' => 'Color020',
            '#509fc9' => 'Color030',
            '#5885cf' => 'Color040',
            '#9062c0' => 'Color050',
            '#d09a45' => 'Color060',
            '#e4b138' => 'Color070',
            '#ee903c' => 'Color080',
            '#f08500' => 'Color081',
            '#a9d92d' => 'Color082',
            '#dd6549' => 'Color090',
            '#cc463d' => 'Color100',
            '#cf3e36' => 'Color101',
            '#5E6671' => 'Color102',
        ];

        $model->color = $colors[$card['base_info']['color']];
        $model->notice = $card['base_info']['notice'];
        $model->description = $card['base_info']['description'];
        $model->prerogative = $card['prerogative'];
        $model->wx_activate_after_submit_url = $card['wx_activate_after_submit_url'];
        $model->quantity = $card['base_info']['sku']['quantity'];
        $model->total_quantity = $card['base_info']['sku']['total_quantity'];
        $model->cost_money_unit = $card['bonus_rule']['cost_money_unit'];
        $model->increase_bonus = $card['bonus_rule']['increase_bonus'];
        $model->max_increase_bonus = $card['bonus_rule']['max_increase_bonus'];
        $model->init_increase_bonus = $card['bonus_rule']['init_increase_bonus'];
        $model->cost_bonus_unit = $card['bonus_rule']['cost_bonus_unit'];
        $model->reduce_money = $card['bonus_rule']['reduce_money'];
        $model->least_money_to_use_bonus = $card['bonus_rule']['least_money_to_use_bonus'];
        $model->max_reduce_bonus = $card['bonus_rule']['max_reduce_bonus'];

        // $wx_activate_after_submite_url = 'http://winshare.onthemooner.com/index.php/wechat-member-card/activate';

        // $data = [
        //     'card_id' => $model->card_id,
        //     'member_card' => [
        //         'custom_field1' => [
        //             'name_type' => 'FIELD_NAME_TYPE_LEVEL',
        //             'url' => 'http://winshare.onthemooner.com/index.php/wechat-member-card/level',
        //         ],
        //         'wx_activate_after_submit_url' => $wx_activate_after_submite_url,
        //     ],
        // ];
        // $re = Wechat::card_update($data);
        // $this->bp($re);

        if ($model->load(Yii::$app->request->post())) {
            // $this->bp($model);

            $data = [
                'card_id' => $model->card_id,
                'member_card' => [
                    'base_info' => [
                        'logo_url' => $model->logo_url, // 卡券的商户logo，建议像素为300*300 必填
                        'code_type' => $model->code_type, // Code展示类型 必填
                        // 'brand_name' => $model->brand_name, // 商户名字,字数上限为12个汉字 必填
                        'title' => $model->title, // 卡券名，字数上限为9个汉字 必填
                        'color' => $model->color, // 券颜色。按色彩规范标注填写Color010-Color100 必填
                        'notice' => $model->notice, // 卡券使用提醒，字数上限为16个汉字 必填
                        'description' => $model->description, // 卡券使用说明，字数上限为1024个汉字 必填
                    ],
                    // 'advanced_info' => [],
                    'prerogative' => $model->prerogative, // 会员卡特权说明,限制1024汉字 必填
                    'wx_activate_after_submit_url' => $model->wx_activate_after_submit_url,
                    'bonus_rule' => [ // 选填
                        'cost_money_unit' => $model->cost_money_unit, // 消费金额,以分为单位
                        'increase_bonus' => $model->increase_bonus, // 对应增加的积分
                        'max_increase_bonus' => $model->max_increase_bonus, // 用户单次可获取的积分上限
                        'init_increase_bonus' => $model->init_increase_bonus, // 初始设置积分
                        'cost_bonus_unit' => $model->cost_bonus_unit, // 每使用多少积分
                        'reduce_money' => $model->reduce_money, // 抵扣xx元，（这里以分为单位）
                        'least_money_to_use_bonus' => $model->least_money_to_use_bonus, // 抵扣条件，满xx元（这里以分为单位）可用
                        'max_reduce_bonus' => $model->max_reduce_bonus, // 抵扣条件，单笔最多使用xx积分
                    ],
                ],
            ];

            // $this->bp(Api::toJSON($data));
            $re = Wechat::card_update($data);
            // $this->bp($re);

            if ($re['errmsg'] != 'ok') {
                Yii::$app->session->setFlash('error', $re['errmsg']);
            } else {
                $model->save(false);
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing MemberCard model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if ($model) {
            $card_id = $model['card_id'];
            $re = Wechat::card_delete(['card_id' => $card_id]);
            if ($re['errmsg'] != 'ok') {
                Yii::$app->session->setFlash('error', $re['errmsg']);
            } else {
                $this->findModel($id)->delete();
                Yii::$app->session->setFlash('success', $re['errmsg']);
            }
        }

        return $this->redirect(['index']);
    }

    /**
     * Finds the MemberCard model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return MemberCard the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = MemberCard::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
